package org.bes.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarUtils {

    public static void compareJars(File jar1, File jar2) throws IOException {
        try (JarFile jarFile1 = new JarFile(jar1);
             JarFile jarFile2 = new JarFile(jar2)) {

            Enumeration<JarEntry> entries1 = jarFile1.entries();
            Enumeration<JarEntry> entries2 = jarFile2.entries();

            Map<String, byte[]> jar1Files = new HashMap<>();
            Map<String, byte[]> jar2Files = new HashMap<>();

            // Read all files from the first JAR
            while (entries1.hasMoreElements()) {
                JarEntry entry = entries1.nextElement();
                if (entry.getName().endsWith(".class")) {
                    byte[] content = readJarEntry(jarFile1, entry);
                    jar1Files.put(entry.getName(), content);
                }
            }

            // Read all files from the second JAR
            while (entries2.hasMoreElements()) {
                JarEntry entry = entries2.nextElement();
                if (entry.getName().endsWith(".class")) {
                    byte[] content = readJarEntry(jarFile2, entry);
                    jar2Files.put(entry.getName(), content);
                }
            }

            // Compare the files
            Set<String> allEntries = new HashSet<>();
            allEntries.addAll(jar1Files.keySet());
            allEntries.addAll(jar2Files.keySet());

            for (String entry : allEntries) {
                byte[] content1 = jar1Files.get(entry);
                byte[] content2 = jar2Files.get(entry);

                if (content1 == null) {
                    System.out.println("File " + entry + " is missing in the first JAR.");
                } else if (content2 == null) {
                    System.out.println("File " + entry + " is missing in the second JAR.");
                } else if (!Arrays.equals(content1, content2)) {
                    System.out.println("File " + entry + " differs between the two JARs.");
                }
            }
        }
    }

    private static byte[] readJarEntry(JarFile jarFile, JarEntry entry) throws IOException {
        try (InputStream inputStream = jarFile.getInputStream(entry)) {
            return inputStream.readAllBytes();
        }
    }
}
